import 'package:cat_eye/base/base_chang_notifier.dart';
import 'package:cat_eye/bean/home_body_bean.dart' as home_body_bean;
import 'package:cat_eye/config/url_config.dart';
import 'package:cat_eye/http/http_manager.dart';
import 'package:cat_eye/util/loading_state_widget_util.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

/*
* @Package: view_model.home_view_model
* @ClassName: home_body_view_model
* @Author: szj
* @CreateDate: 7/28/21 3:48 PM
*/
class HomeBodyViewModel extends BaseChangNotifier {
  List<home_body_bean.ItemList> bannerList = [];

  List<home_body_bean.ItemList> videoList = [];

  //下一页的数据[url]
  String nextPageUrl;

  //上拉加载/下拉刷新控制器
  RefreshController refreshController =
      RefreshController(initialRefresh: false);

  /*
   *   加载下一页数据
   */
  void requestHttpHomeBodyVideo() {
    HttpManager.requestHttpData(nextPageUrl,
        onSuccess: (date) {
          // type = LoadingWidget.DONG;
          var videoBean = home_body_bean.HomeBodyBean.fromJson(date);
          videoList.addAll(videoBean.issueList[0].itemList);
        },
        onFail: (e) {
          type = LoadingWidget.ERROR;
        },
        complete: () => notifyListeners());
  }

  /*
   *  上拉加载更多
   */
  void loadMore() async {
    await HttpManager.requestHttpData(
        //请求下一页接口
        nextPageUrl,
        onSuccess: (s) {
          //请求成功
          type = LoadingWidget.DONG;

          var bean = home_body_bean.HomeBodyBean.fromJson(s);

          //三方控制器请求网络数据
          refreshController.loadComplete();

          //保存下一页的数据
          nextPageUrl = bean.nextPageUrl;

          //请求下一页数据
          requestHttpHomeBodyVideo();
        },
        onFail: (s) {
          type = LoadingWidget.ERROR;
          //三方控制器 请求失败
          refreshController.loadFailed();
        },
        //完成请求通知刷新
        complete: () => notifyListeners());
  }

  //请求网络数据 / 下拉刷新
  void requestHttpData() async {
    //网络数据请求中
    type = LoadingWidget.LOADING;
    //下拉刷新时，保证列表中没有数据
    videoList.clear();
    //清空Banner数据避免下拉刷新数据重复
    bannerList.clear();

    await HttpManager.requestHttpData(
      UrlConfig.feedUrl,
      onSuccess: (s) {
        //请求成功
        type = LoadingWidget.DONG;

        var bean = home_body_bean.HomeBodyBean.fromJson(s);

        buildBannerList(bean);

        //当下一个接口请求回来时候,关闭刷新按钮
        refreshController.refreshCompleted();
        refreshController.footerMode.value = LoadStatus.canLoading;

        //保存下一页的数据
        nextPageUrl = bean.nextPageUrl;
        //请求下一页数据
        requestHttpHomeBodyVideo();
      },
      onFail: (s) {
        //请求失败
        type = LoadingWidget.ERROR;
      },
    );
  }

  //Banner数据
  void buildBannerList(home_body_bean.HomeBodyBean bean) {
    //拿到Banner数据添加到集合中
    bean.issueList[0].itemList.forEach((element) {
      if (element.type != "banner2" &&
          element.data != null &&
          element.data.cover != null) {
        bannerList.add(element);
      }
    });
  }
}
